package com.b.service.impl;

import com.b.dao.ProductCategoryMapper;
import com.b.domain.ProductCategory;
import com.b.repository.ProductCategoryRepository;
import com.b.service.ProductCategoryService;
import jakarta.annotation.Resource;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.SearchPage;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ProductCategoryServiceImpl implements ProductCategoryService {

    @Resource
    private ProductCategoryMapper productCategoryMapper;
    @Resource
    private ProductCategoryRepository productCategoryRepository;

    @Override
    @Transactional
    public boolean deleteByPrimaryKey(Integer id) {
        try {
            productCategoryMapper.deleteByPrimaryKey(id);
            productCategoryRepository.deleteById(id);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public int insert(ProductCategory record) {
        return productCategoryMapper.insert(record);
    }

    @Override
    public int insertSelective(ProductCategory record) {
        return productCategoryMapper.insertSelective(record);
    }

    @Override
    public ProductCategory selectByPrimaryKey(Integer id) {
        return productCategoryMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(ProductCategory record) {
        return productCategoryMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(ProductCategory record) {
        return productCategoryMapper.updateByPrimaryKey(record);
    }

    @Override
    public List<ProductCategory> getAll() {
        return productCategoryMapper.getAll();
    }

    @Override
    public SearchPage<ProductCategory> findProductCategoryByTypeLike(String type, PageRequest pageRequest) {
        return productCategoryRepository.findProductCategoryByTypeLike(type, pageRequest);
    }

    @Override
    @Transactional
    public boolean add(ProductCategory productCategory) {
        try {
            //先保存到数据库
            productCategoryMapper.insert(productCategory);
            //再保存到es
            productCategoryRepository.save(productCategory);
            return true;

        } catch (Exception e) {
            return false;
        }
    }

    @Override
    @Transactional
    public boolean update(ProductCategory productCategory) {
        try {
            //先更新数据库
            productCategoryMapper.updateByPrimaryKey(productCategory);
            //再更新es
            productCategoryRepository.save(productCategory);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
